package net.tv90.auth.utils;

import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
public class SMSCodeUtils {

    Random random = new Random();
    String[] zeros = {"00000", "0000", "000", "00", "0", ""};

    @CachePut(value = "smsCode", key = "#tel")
    public String generateCodeForTel(String tel) {
        int hash = tel.hashCode();
        int encryption = 123456;
        long rehash = hash ^ encryption;
        long time = System.currentTimeMillis();
        rehash ^= time;
        long code = rehash % 1000000;
        code = code < 0 ? -code : code;
        String codeStr = code + "";
        int length = codeStr.length();
        return zeros[length - 1] + codeStr;
    }

    @CachePut(value = "smsCode", key = "#email")
    public String generateCodeForEmail(String email) {
        int base = random.nextInt(0, Integer.MAX_VALUE) % 1000000;
        String codeStr = String.valueOf(base);
        int length = codeStr.length();
        return zeros[length - 1] + codeStr;
    }

    @Cacheable(value = "smsCode", key = "#tel")
    public String getCodeFromCacheForTel(String tel) {
        return null;
    }

    @Cacheable(value = "smsCode", key = "#email")
    public String getCodeFromCacheForEmail(String email) {
        return null;
    }


}
